import os

def h2_to_inc(line):
    ''' 把二级标题转为新文件 '''
    if is_h2(line):
        return "![[" + h2_filename(line) + "]]"
    return line

def h2_to_incs(lines):
    result = []
    for line in lines:
        result.append(h2_to_inc(line))
    return result    

def read(filename):
    ''' 读取文件。得到列表 '''
    effects = []
    with open(filename, mode='r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            if line.strip() != "":
                effects.append(line.strip())
    return effects

def is_h1(line):
    return line.startswith('# ')

def is_h2(line):
    return line.startswith('## ')

def h2_filename(line):
    return line[3:].replace(' ', '-')

def create_h2_file(line, dir):
    ''' 创建文件 '''
    filename = os.path.join(dir, h2_filename(line) + ".md")
    if not os.path.exists(filename):
        with open(filename, mode="w", encoding='utf-8') as f:
            f.write(line + "\n")
        

def create_h2_files(lines, dir):
    ''' 创建文件 '''
    for line in lines:
        if is_h2(line):
            create_h2_file(line, dir)
        

def run(filename):
    lines = read(filename)
    dir = os.path.dirname(filename)
    create_h2_files(lines, dir)
    converted = h2_to_incs(lines)
    with open(filename, mode='w', encoding='utf-8') as f:
        for line in converted:
            f.write(line + "\n")
            f.write("\n")
    
    
if __name__ == "__main__":
    run("D:\\LiuZhaoHui\\私人网盘\\笔记\\Obsidian\\工作笔记\\vue\\element\\目录.md")